/*
 * @Description: 通知列表
 * @Author: Zzt
 * @Date: 2023-02-20 15:49:41
 * @LastEditTime: 2023-02-28 17:14:20
 */
import { publishAnnouncement } from '@/api/announcement/announcement';
import { formatDate } from '@/utils';
import { Button, Popover, Table } from 'antd';
import { ColumnsType } from 'antd/lib/table';
import { useEffect, useMemo, useState } from 'react';
import { useAnnouncementMgtContext } from '../contexts/AnnouncementMgtContext';
import EditAnnounce from './dialogs/EditAnnounce';
import PreviewAnnounce from './dialogs/PreviewAnnounce';
import UnitSelection from './dialogs/UnitSelection';
import Withdraw from './dialogs/Withdraw';
interface DataType {
  title?: string;
  channel?: string;
  build?: any;
  author?: string;
  release?: any;
  status?: any;
}
const content = (text: any) => <>{text}</>;

const PageList = () => {
  const {
    selectItems,
    setSelectKey,
    announceList,
    noticeTypeId,
    getAnnounceList,
    delAnnounce,
    statusFilter,
    editStatus
  } = useAnnouncementMgtContext();
  // 获取列表开始
  const [listQuery, setListQuery] = useState({
    pageNo: 1,
    pageSize: 10,
    param: {}
  });
  const [loading, setLoading] = useState(false);
  const [total, setTotal] = useState(0);

  /* 切换页码查找列表 */
  useEffect(() => {
    if (listQuery) {
      let params = {};
      noticeTypeId === 0 ? (params = {}) : (params = { noticeTypeId });
      setLoading(true);
      getAnnounceList({ ...listQuery, param: params })
        .then((res: any) => {
          setTotal(res?.totalCount);
          setTimeout(() => {}, 2000);
        })
        .finally(() => {
          setLoading(false);
        });
    }
  }, [listQuery, noticeTypeId]);
  /**
   * @description 切换页码触发
   * @param {number} page 页码
   * @param {number} pageSize 每页条目数
   */
  const pageChange = (page: number, pageSize: number) => {
    setListQuery((state) => ({
      ...state,
      pageNo: page,
      pageSize
    }));
  };
  /**
   * @description : 表格选项相关设置
   * @param {number} selectedRowKeys 选择的项目的KEY
   */
  const onSelectChange = (selectedRowKeys: number[]) => {
    setSelectKey(selectedRowKeys);
  };
  /**
   * @description:  表格多选配置
   */
  const rowSelection = {
    selectItems,
    onChange: onSelectChange
  };
  // 获取列表结束

  // 弹窗相关按钮
  /* 撤销弹窗 */
  const [withdrawData, setWithdrawData] = useState({});
  const [withdrawVisible, setWithdrawVisible] = useState(false);
  /* 详情数据 */
  const [announceData, setAnnounceData] = useState({});
  const [announceVisible, setAnnounceVisible] = useState(false);
  /* 编辑弹窗 */
  const [editannounceData, setEditAnnounceData] = useState({});
  const [editannounceVisible, setEditAnnounceVisible] = useState(false);
  /* 预览弹窗 */
  const [previewData, setPreviewData] = useState({});
  const [previewVisible, setPreviewVisible] = useState(false);
  /* 单位选择 */
  const [unitData, setUnitData] = useState({});
  const [unitVisible, setUnitVisible] = useState(false);
  /* 撤回 */
  const setWithdraw = (data: any) => {
    setWithdrawData(data);
    setWithdrawVisible(true);
  };
  /* 详情 */
  const ShowAnnounce = (data: any) => {
    setAnnounceData(data);
    setAnnounceVisible(true);
  };
  /* 编辑 */
  const ShowEditAnnounce = (data: any) => {
    setEditAnnounceData(data);
    setEditAnnounceVisible(true);
  };
  /* 预览 */
  const showPreviewData = (data: any) => {
    setPreviewData(data);
    setPreviewVisible(true);
  };
  /* 单位选择 */
  const unitSelect = (data: any) => {
    setUnitData(data);
    setUnitVisible(true);
  };
  // 弹窗相关结束
  /* 发布 */
  const Release = (data: any) => {
    publishAnnouncement(data.id).then(editStatus({ ...data, status: 2 }));
  };
  /* 表格配置 */
  const columns: ColumnsType<DataType> = [
    {
      title: '标题',
      dataIndex: 'title',
      key: 'title',
      align: 'center'
    },
    {
      title: '频道',
      dataIndex: 'noticeTypeName',
      key: 'noticeTypeName',
      align: 'center'
    },
    {
      title: '作者',
      dataIndex: 'author',
      key: 'author',
      align: 'center'
    },
    {
      title: '创建日期',
      dataIndex: 'createdTime',
      key: 'createdTime',
      align: 'center',
      render: (text: any) => <span>{formatDate(text)}</span>
    },
    {
      title: '发布日期',
      dataIndex: 'publicTime',
      key: 'publicTime',
      align: 'center',
      render: (text: any) => <span>{formatDate(text)}</span>
    },
    {
      title: '撤回原因',
      dataIndex: 'reason',
      key: 'reason',
      align: 'center',
      render: (text, record) =>
        record.status === 3 && (
          <Popover placement="bottom" content={() => content(text)} trigger="click">
            <Button type="link">撤回原因</Button>
          </Popover>
        )
    },
    {
      title: '状态',
      dataIndex: 'status',
      key: 'status',
      align: 'center',
      render: (text) => statusFilter(text)
    },
    {
      title: '操作',
      dataIndex: 'action',
      key: 'action',
      align: 'center',
      width: '30%',
      render: (_: any, record: any) => {
        return (
          <>
            {record.status === 1 && (
              <Button type="link" onClick={() => ShowEditAnnounce(record)}>
                编辑
              </Button>
            )}
            {/* {record.status === 1 && (
              <Button type="link" onClick={() => unitSelect(record)}>
                选择单位
              </Button>
            )} */}
            {record.status === 1 && (
              <Button type="link" onClick={() => Release(record)}>
                发布
              </Button>
            )}
            <Button type="link" onClick={() => ShowAnnounce(record)}>
              详情
            </Button>
            {record.status === 2 && (
              <Button type="link" onClick={() => setWithdraw(record)}>
                撤回
              </Button>
            )}
            <Button type="link" onClick={() => showPreviewData(record)}>
              预览
            </Button>
            <Button type="link" danger onClick={() => delAnnounce(record.id)}>
              删除
            </Button>
          </>
        );
      }
    }
  ];

  return (
    <>
      <Table
        dataSource={announceList}
        loading={loading}
        rowKey="id"
        size="small"
        scroll={{ x: 'max-content' }}
        bordered
        rowSelection={rowSelection}
        pagination={{
          current: listQuery.pageNo,
          pageSize: listQuery.pageSize,
          total,
          onChange: pageChange
        }}
        columns={columns}
      />
      {useMemo(
        () => (
          <Withdraw
            onClose={() => setWithdrawVisible(false)}
            visible={withdrawVisible}
            withdrawData={withdrawData}
          />
        ),
        [withdrawVisible, withdrawData]
      )}
      {useMemo(
        () => (
          <EditAnnounce
            onClose={() => setAnnounceVisible(false)}
            visible={announceVisible}
            data={announceData}
            view={true}
            disable={true}
          />
        ),
        [announceVisible, announceData]
      )}
      {useMemo(
        () => (
          <EditAnnounce
            onClose={() => setEditAnnounceVisible(false)}
            visible={editannounceVisible}
            data={editannounceData}
            view={false}
            disable={false}
          />
        ),
        [editannounceVisible, editannounceData]
      )}
      {useMemo(
        () => (
          <PreviewAnnounce
            onClose={() => setPreviewVisible(false)}
            visible={previewVisible}
            data={previewData}
          />
        ),
        [previewVisible, previewData]
      )}
      {useMemo(
        () => (
          <UnitSelection
            onClose={() => setUnitVisible(false)}
            visible={unitVisible}
            data={unitData}
          />
        ),
        [unitVisible, unitData]
      )}
    </>
  );
};
export default PageList;
